package com.ruoyi.web.controller.system;

import com.ruoyi.system.domain.mongodb.Users;
import com.ruoyi.system.mongo.StudentDao;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author HP
 * @Date 2021/3/18
 * @Description TODO
 */
@Controller
@RequestMapping("/wx")
public class WxController {
    private String appid="wx88890f425ecb1696";
    private String appsecret="ed89e10d75396fa94a85b7c8c9e36d1a";
    @Autowired
    private StudentDao studentDao;

    @RequestMapping("/getRedirect") /*主管微信登录回调*/
    public void  getRedirect(HttpServletRequest request, HttpServletResponse response,RedirectAttributes redirectatt) throws IOException, ServletException {
        String code = request.getParameter("code");
//String state = request.getParameter("state");
//通过code获取access_token
        String token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
        System.out.println(appid);
        System.out.println(token_url);
        //token_url =  token_url.replace("APPID",appid).replace("SECRET",appsecret).replace("CODE",code);
        String resToken = WxController.interfaceUtil(token_url);
        System.out.println(token_url);
        JSONObject res_json = JSONObject.fromObject(resToken);
        /*微信openid*/
        String openid = (String) res_json.get("openid");
        System.out.println("openid:"+openid);
//根据openid访问数.库判断是否是第一次登录，第一次需要绑定账号。
//逻辑处理
        String access_token = (String) res_json.get("access_token");

        //返回结果判断
        Users users = studentDao.findUserOpenid(openid);

        if (users==null){
            /*跳转绑定账号页面*/
            response.sendRedirect("http://www.maker.band/bindingAccountNumber?openid="+openid+"&access_token="+access_token+"");
        }else {
            /*逻辑处理*/

            /*直接登录*/
            response.sendRedirect("http://www.maker.band/myWxLogin?openid="+openid);
        }
    }

    /*调取微信接口封装*/
    public static String interfaceUtil(String path) {
        try {
            URL url = new URL(path);
//打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            PrintWriter out = null;
//请求方式
//          conn.setRequestMethod("POST");
//           //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
//设置是否向httpUrlConnection输出，设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
//最常用的Http请求无非是get和post，get请求可以获取静态页面，也可以把参数放在URL字串后面，传递给servlet，
//post与get的 不同之处在于post的参数不是放在URL字串里面，而是放在http请求的正文内。
            conn.setDoOutput(true);
            conn.setDoInput(true);
//获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
//发送请求参数即数据
//out.print(data);
//缓冲数据
            out.flush();
//获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
//构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
//System.out.println(str);
                return str;
            }
//关闭流
            is.close();
//断开连接，最好写上，disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
//固定多线程的话，如果不disconnect，链接会增多，直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
//System.out.println("完整结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
